package servlets.games;

import hibernate.method.RateMethods;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class addGameRate
 */
@WebServlet("/addGameRate")
public class addGameRate extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public addGameRate() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String game = (String) request.getParameter("game_id");
		String user = (String) request.getParameter("user");
		String rate = (String) request.getParameter("rate");
		
		int game_id = Integer.parseInt(game);
		int user_id = Integer.parseInt(user);
		int rate1 = Integer.parseInt(rate);
		
		PrintWriter out = response.getWriter();
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		RateMethods rm = new RateMethods();
		session.beginTransaction();
		
		if(rm.findGameRateByUserGame(sessionFactory, session, user_id, game_id).isEmpty())
		rm.addGameRate(sessionFactory, session, user_id, game_id, rate1);
		else rm.editGameRate(sessionFactory, session, rm.findGameRateByUserGame(sessionFactory, session, user_id, game_id).get(0), rate1);
		
		
		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Ocena zostala dodana pomyslnie\"); window.location.href = \"social/index.jsp?page=games&group=searchGame\";</script>");
		} catch (Exception e) {			
			out.println("<script type=\"text/javascript\">alert(\"Ocena nie zostala dodana\"); window.location.href = \"social/index.jsp?page=games&group=searchGame\";</script>");
		}
				
		
	}

}
